<template>
        <div class="container">
        <!-- 头部 -->
        <div class="card" style="margin-bottom: 5px;">
                <el-input placeholder="搜索" :prefix-icon="Search"  style="width: 240px; margin-right: 5px;" v-model="data.name"></el-input>
                <el-button type="primary" @click="getMessage">查 询</el-button>
                <el-button type="warning" @click="reset">重 置</el-button>
        </div>
        <!-- 内容区1 -->
        <div class="card" style="display: flex; align-items: center;">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="warning" @click="batch">批量删除</el-button>
            <el-upload
                class="excel-upload"
                action="http://localhost:8080/employee/import"
                :show-file-list="false"
                :on-success="importSuccess"
                style="margin: 0 10px 0 10px;"
                >
                <el-button type="primary">导入</el-button>        
            </el-upload>
            
            <el-button type="success" @click="dataExport">导出</el-button>
        </div>
        <!-- 内容区2 -->
        <div class="card" style="margin-top: 5px;">
            <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="用户名" prop="username"/>
                <el-table-column label="头像" prop="avatar">
                    <template #default="scope">
                        <img :src="'http://localhost:8080/files/download/' + scope.row.avatar" alt=""/>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" prop="name"/>
                <el-table-column label="性别" prop="sex"/>
                <el-table-column label="工号" prop="no"/>
                <el-table-column label="部门" prop="departmentName"/>
                <el-table-column label="描述" prop="description" show-overflow-tooltip/>
                <el-table-column label="操作"  width="120" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" circle :icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                        <el-button type="danger" circle :icon="DeleteFilled" @click="del(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页组件 -->
         <div class="card">
            <el-pagination
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
            @current-change="getMessage"
            @size-change="getMessage"
            />
         </div>

         <!-- 添加修改员工对话框 -->
         <el-dialog
            v-model="addView"
            title="员工信息"
            width="500"
        >
            <el-form :model="data.form" :rules="data.rules" style="padding: 20px;">
                <el-form-item label="头像">
                    <el-upload
                        class="avatar-uploader"
                        action="http://localhost:8080/files/upload"
                        list-type="picture"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="data.form.avatar" :src="'http://localhost:8080/files/download/' + data.form.avatar" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户名"  prop="username">
                    <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入姓名"/>
                </el-form-item>
                <el-form-item label="员工姓名"  prop="name">
                    <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名"/>
                </el-form-item>
                <el-form-item label="工号"  prop="no">
                    <el-input v-model="data.form.no" autocomplete="off" placeholder="请输入工号"/>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="data.form.departmentId">
                        <el-option v-for="item in data.departmentList" 
                        :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="data.form.sex">
                       <el-radio value="男" label="男"></el-radio> 
                       <el-radio value="女" label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="描述" >
                    <el-input v-model="data.form.description" type="textarea" :row="3" autocomplete="off" placeholder="请输入对员工的描述。。。"/>
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="addView = false">取消</el-button>
                <el-button type="primary" @click="addMessage">确认</el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref,reactive,onMounted } from 'vue';
import {DeleteFilled,Edit,Search,Plus} from '@element-plus/icons-vue'

const addView = ref(false)
const delList = ref([])//删除列表
const data = reactive({
    name:null,
    tableData:[],
    pageSize:10,//分页数量
    pageNum:1,//当前页面
    total:0,//数据总量
    form:{},//要添加的数据
    departmentList:[],//部门种类
    rules:{
        username:[{required:true,message:'请输入账号',trigger:'blur'}],
        name:[{required:true,message:'请输入姓名',trigger:'blur'}],
        no:[{required:true,message:'请输入工号',trigger:'blur'}]
    }
})

//获取信息
const getMessage = () =>{
    request.get('/employee/selectPage',{
        params:{
            pageSize:data.pageSize,
            pageNum:data.pageNum,
            name:data.name
        }
    }).then(res => {
        console.log(res,"res");
        data.tableData = res.data.list
        data.total = res.data.total
    })

    request.get('/department/getAll').then(res =>{        
        data.departmentList = res.data
    })
}

//重置
const reset = () =>{
    data.name = null
    data.pageNum = 1
    data.pageSize = 10
    getMessage()
}

// 图片上传相关逻辑
const handleAvatarSuccess = (file) => {
    // imageUrl.value = URL.createObjectURL(file.raw);
    console.log(file,"file1");
    // 提取文件名
    const url = file.data;
    const fileName = url.split('/').pop();
    data.form.avatar = fileName;
    
};
const beforeAvatarUpload = (file) => {
    console.log(file,"file2");
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
        ElMessage.error('只能上传图片文件！');
    }
    return isImage;
};

//批量删除
const handleSelectionChange = (rows) =>{
    delList.value = rows.map(v => {
        const id = Number(v.id)
        return id
    })
}
const batch = () =>{
    if(delList.value.length !== 0){
        console.log(delList.value,"delList.value");
        ElMessageBox.confirm('删除数据后无法恢复，确认删除吗','确认删除',{type:'warning'}).then(()=>{
            request.delete("/employee/batch",{data:delList.value}).then(res =>{
                if(res.code == '200'){
                    ElMessage.success("成功")
                    getMessage()
                }else{
                    ElMessage.error(res.data);
                }
            }) 
        })
    }else{
        ElMessage.error("请选择要删除的内容")
    }
}

//导入
const importSuccess = (res) =>{
    console.log(res,"import");
    if(res.code=='200'){
        ElMessage.success("导入成功")
        getMessage()
    }else{
        ElMessage.error(data.msg)
    }

}

//导出
const dataExport = () =>{
    window.open('http://localhost:8080/employee/export')
}

const handleUpdate = (row)=>{
    addView.value = true
    data.form = row
}

const handleAdd = () =>{
    addView.value = true
    data.form = {}//初始化数据
}

//编辑信息
const edit = () =>{    
    request.put('/employee/update', data.form).then(res=>{
        if(res.code == '200'){
            ElMessage.success("修改成功")
            addView.value = false
            getMessage()
        }else{
        ElMessage.error(res.msg)
    }
    }) 
}

//删除消息
const del = (row) =>{
    console.log(row.id,"rrrrrrrrrrrrrrow.id");
    request.delete(`/employee/delete/${row.id}`).then(res =>{
        if(res.code == '200'){
            ElMessage.success('删除成功')
            getMessage()//冲洗加载数据
        }else{
            ElMessage.error(res.msg)
        }
    })
}

//增加弹窗
const add = () =>{
    request.post('/employee/add',data.form).then(res=>{
        console.log(res,"ressss");
        if(res.code == '200'){
            ElMessage.success('添加成功')
            getMessage()//冲洗加载数据
            addView.value = false
        }else{
            ElMessage.error(res.msg)
        }  
    })
}


// 增加信息
const addMessage = () => {
    if(data.form.id != null){
        edit()
    }else{
        add()
    }
}

onMounted(()=>{
    getMessage()
})

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.avatar{
    width: 100%;
    height: 100%;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 88px;
  height: 80px;
  text-align: center;
}
</style>
